<template>
  <!-- v-loading="true" -->
  <div>
    <pageSearch :searchFormConfig="searchFormConfig" @searchSubmit="searchSubmit" />
    <pageTable :tableData="tableData" :tableInit="params.tableInit" @sizeChange="sizeChange"
      @currentChange="currentChange" @exportFn="exportExcel" v-loading="loading" @pageAdd="openDialogFn('新增')">
      <template #operation="{ row }">
        <el-button type="primary" link @click="openDialogFn('编辑', row)">编辑</el-button>
        <el-popconfirm title="确认要删除吗?" @confirm="delData(row.id)">
          <template #reference>
            <el-button type="danger" link>删除</el-button>
          </template>
        </el-popconfirm>
      </template>



    </pageTable>

    <Dialog width="40%" ref="DialogRef" :title="typeText" @submit="submitForm(ruleFormRef)"
      @onclose="resetForm(ruleFormRef)">
      <div class="text-red-600 mb-6 pl-12">
        <div>“工作温度”请在产品列表录入</div>
        <div>单位请使用英文单位括号 ---“()”</div>
      </div>
      <el-form v-loading="DialogLoading" ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules"
        label-width="120px" class="demo-ruleForm">
        <el-form-item label="字典名字" prop="name">
          <el-input v-model="ruleForm.name" autocomplete="off" />
        </el-form-item>

        <el-form-item label="字典说明">
          <el-input v-model="ruleForm.description" autocomplete="off" />
        </el-form-item>

        <el-form-item label="字典参数" prop="list" v-loading="popLoading">
          <template v-for="(item, index) in ruleForm.list" :key="index">

            <el-row class="w-full mt-4" :gutter="20">


              <el-col :span="10">
                <el-input placeholder="请输入" v-model="item.name" autocomplete="off" />
              </el-col>


              <el-col :span="7">
                <el-select style="width: 100%" v-model="item.searchtype" placeholder="请选择">
                  <el-option v-for="option in typeOpt" :key="option.id" :label="option.name" :value="option.id" />
                </el-select>
              </el-col>


              <el-col :span="5">
                <el-input placeholder="请输入顺序" type="number" v-model="item.px" autocomplete="off" />
              </el-col>

              <el-col :span="2">

                <el-popconfirm title="确定要删除吗?" @confirm="delItem(item, index)">
                  <template #reference>
                    <div class="flex items-center h-full min-w-[25px] cursor-pointer">
                      <img class="w-[25px] h-[25px]" src="../../assets/product/del.png" alt="">
                    </div>
                  </template>
                </el-popconfirm>



              </el-col>

              <template v-if="item.searchtype == 1">
                <tagCommon v-model:searchcheckbox='item.searchcheckbox'></tagCommon>

              </template>
              <template v-if="item.searchtype == 2">
                <el-col :span="24" class="mt-4">
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <el-input v-model="item.mini" placeholder="最小值" />
                    </el-col>
                    <el-col :span="2">
                      <div class="flex justify-center">
                        至
                      </div>
                    </el-col>
                    <el-col :span="8">
                      <el-input v-model="item.maxi" placeholder="最大值" />
                    </el-col>
                    <el-col :span="6">
                      <el-input v-model="item.step" placeholder="步进值" />
                    </el-col>
                  </el-row>

                </el-col>
              </template>


            </el-row>
          </template>

        </el-form-item>





        <el-form-item>
          <div style="border: 1px solid #D9E1EA;"
            class="w-[36px] h-[36px] flex justify-center items-center cursor-pointer" @click="addList">
            <el-icon>
              <Plus />
            </el-icon>
          </div>
        </el-form-item>

      </el-form>
    </Dialog>


  </div>
</template>

<script setup lang="ts">
import pageSearch from "@/components/base-ui/page-search";
import pageTable from "@/components/base-ui/page-table";
import Dialog from "@/components/base-ui/dialog";
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules, ElInput } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { clone } from "@pureadmin/utils";
import tagCommon from './components/tagCommon.vue'
import { searchFormConfig } from "./config/dictionarySearch.config";
import { tableInit } from "./config/dictionaryTable.config";
import { productdictionaryinsert, productdictionarydelinfo, productdictionarychange, getproductdictionaryselpage, productdictionaryselzdandzdinfo, productdictionarydelzd } from '@/api/productdictionary'
import { usepageTable } from '@/components/base-ui/page-table/usePageTable'
import { message } from "@/utils/message";


const {
  exportExcel,
  tableData,
  getData,
  addData,
  amendData,
  delData,
  params,
  loading,
  sizeChange,
  currentChange,
  searchSubmit,
  DialogRef,
  openDialog,
} = usepageTable({
  tableInit,
  getRes: getproductdictionaryselpage,
  addRes: productdictionaryinsert,
  delRes: productdictionarydelinfo,
  updateRes: productdictionarychange
})

getData()

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  name: '',
  description: '',
  list: [],
})






const validateList = (rule: any, value: any, callback: any) => {
  if (value.length === 0) {
    callback(new Error('请创建字典参数'))
  } else {
    let filterArray = value.filter(v => Boolean(v.name));
    if (filterArray.length !== value.length) {
      callback(new Error('请正确填写字典参数字段'))
    } else {
      callback()
    }
  }
}


const rules = reactive<FormRules<typeof ruleForm>>({
  name: [
    { required: true, message: '请填写字典名称', trigger: 'blur' },
  ],
  list: [
    { validator: validateList, trigger: 'blur' }
  ],

})
const typeText = ref('')
const handleID = ref(null)
const openDialogFn = (text, row) => {
  typeText.value = text
  if (row) {
    handleID.value = row.id
    const temporary = clone(row, true);
    Object.keys(ruleForm).forEach((key) => ruleForm[key] = temporary[key])
    getDetail(row.id)
  }
  openDialog()
}

const popLoading = ref(false)
const getDetail = (id) => {
  popLoading.value = true
  productdictionaryselzdandzdinfo(id).then(res => {
    let temporaryList = res.result.map(v => {
      if (!Array.isArray(v.searchcheckbox)) {
        v.searchcheckbox = []
      }
      return v
    })
    ruleForm.list = temporaryList
  }).finally(() => {
    popLoading.value = false
  })
}

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log(ruleForm)
      let arrList = []
      let flag = true
      ruleForm.list.forEach((v) => {
        if (arrList.includes(v.name)) {
          message(`${v.name}存在多次，请删除重复项`, { type: "warning" });
          flag = false
        } else {
          arrList.push(v.name)
        }
      })
      if (!flag) return
      if (typeText.value === '新增') {
        addData(ruleForm)
      } else {
        let Q = clone(ruleForm, true);
        Q.id = handleID.value
        amendData(Q)
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()

  ruleForm.name = ''
  ruleForm.description = ''
  ruleForm.list = []
  handleID.value = null
  typeText.value = ''
}

const typeOpt = [
  { name: '关键字', id: 0 },
  { name: '多选框', id: 1 },
  { name: '数值区间', id: 2 },
]




const addList = () => {
  ruleForm.list.push({
    name: '',
    searchtype: 0,
    searchcheckbox: [],
    maxi: '',
    mini: '',
    step: '',
    px: ''
  })
}

const DialogLoading = ref(false)
const delItem = (item, index) => {
  console.log(item, 'item')
  if (item.id) {
    DialogLoading.value = true
    productdictionarydelzd(item.id).then(res => {
      ruleForm.list.splice(index, 1)
    }).finally(() => {
      DialogLoading.value = false
    })
  } else {
    ruleForm.list.splice(index, 1)
  }

}

</script>

<style scoped></style>
